using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;

namespace GetTogether.Utility
{
    public class RequestHelper
    {
        public static string GetRequest(string url, int timeout)
        {
            return GetRequest(url, "", "POST", "text/xml", timeout);
        }
        
        public static string GetRequest(string url, string post_data, int timeout)
        {
            return GetRequest(url, post_data, "POST", "text/xml", timeout);
        }
        
        public static string GetRequest(string url, string post_data, string method, string content_type, int timeout)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            if (timeout > 0) req.Timeout = timeout;
            byte[] request_bytes = System.Text.Encoding.UTF8.GetBytes(post_data);
            req.Method = method;//"POST";
            req.ContentType = content_type;//"text/xml,application/x-www-form-urlencoded
            req.ContentLength = request_bytes.Length;
            Stream request_stream = req.GetRequestStream();
            request_stream.Write(request_bytes, 0, request_bytes.Length);
            request_stream.Close();
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.UTF8);
            string ret = sr.ReadToEnd();
            sr.Close();
            res.Close();
            return ret;
        }

        public static string PostModel(string url, string param, int timeout)
        {
            return PostModel(url, param, Encoding.UTF8, timeout);
        }
        
        public static string PostModel(string url, string param, Encoding encoding,int timeout)
        {
            Encoding encode = encoding;
            byte[] arrB = encode.GetBytes(param);
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            if (timeout > 0) myReq.Timeout = timeout;
            myReq.Method = "POST";
            myReq.ContentType = "application/x-www-form-urlencoded";
            myReq.ContentLength = arrB.Length;
            Stream outStream = myReq.GetRequestStream();
            outStream.Write(arrB, 0, arrB.Length);
            outStream.Close();
            WebResponse myResp = null;
            try
            {
                myResp = myReq.GetResponse();
            }
            catch
            {

            }
            Stream ReceiveStream = myResp.GetResponseStream();
            StreamReader readStream = new StreamReader(ReceiveStream, encode);
            Char[] read = new Char[256];
            int count = readStream.Read(read, 0, 256);
            string str = null;
            while (count > 0)
            {
                str += new String(read, 0, count);
                count = readStream.Read(read, 0, 256);
            }
            readStream.Close();
            myResp.Close();
            return str;
        }

        public class RequestProperty
        {
            private string _Address;

            public string Address
            {
                get { return _Address; }
                set { _Address = value; }
            }
            private int _Timeout;

            public int Timeout
            {
                get { return _Timeout; }
                set { _Timeout = value; }
            }
            private string _ContentType;

            public string ContentType
            {
                get { return _ContentType; }
                set { _ContentType = value; }
            }
            private string _Method;

            public string Method
            {
                get { return _Method; }
                set { _Method = value; }
            }
            private string[] _Headers;

            public string[] Headers
            {
                get { return _Headers; }
                set { _Headers = value; }
            }
            private string _UserAgent;

            public string UserAgent
            {
                get { return _UserAgent; }
                set { _UserAgent = value; }
            }
            private string _Referer;

            public string Referer
            {
                get { return _Referer; }
                set { _Referer = value; }
            }
            private string _Accept;

            public string Accept
            {
                get { return _Accept; }
                set { _Accept = value; }
            }
            private string _Expect;

            public string Expect
            {
                get { return _Expect; }
                set { _Expect = value; }
            }


            private bool _UseDefaultCredential;

            public bool UseDefaultCredential
            {
                get { return _UseDefaultCredential; }
                set { _UseDefaultCredential = value; }
            }
            private string _BasicAuthUserName;

            public string BasicAuthUserName
            {
                get { return _BasicAuthUserName; }
                set { _BasicAuthUserName = value; }
            }
            private string _BasicAuthPassword;

            public string BasicAuthPassword
            {
                get { return _BasicAuthPassword; }
                set { _BasicAuthPassword = value; }
            }
            private bool _AllowAutoRedirect;

            public bool AllowAutoRedirect
            {
                get { return _AllowAutoRedirect; }
                set { _AllowAutoRedirect = value; }
            }
            private bool _AllowWriteStreamBuffering;

            public bool AllowWriteStreamBuffering
            {
                get { return _AllowWriteStreamBuffering; }
                set { _AllowWriteStreamBuffering = value; }
            }
            private bool _KeepAlive;

            public bool KeepAlive
            {
                get { return _KeepAlive; }
                set { _KeepAlive = value; }
            }
            private bool _Pipelined;

            public bool Pipelined
            {
                get { return _Pipelined; }
                set { _Pipelined = value; }
            }
            private bool _PreAuthenticate;

            public bool PreAuthenticate
            {
                get { return _PreAuthenticate; }
                set { _PreAuthenticate = value; }
            }
            private bool _SendChunked;

            public bool SendChunked
            {
                get { return _SendChunked; }
                set { _SendChunked = value; }
            }
            private string _TransferEncoding;

            public string TransferEncoding
            {
                get { return _TransferEncoding; }
                set { _TransferEncoding = value; }
            }
            private string _MediaType;

            public string MediaType
            {
                get { return _MediaType; }
                set { _MediaType = value; }
            }

            public RequestProperty()
            {

            }
        }
        public static string SendRequest(string requestContent, RequestProperty properties)
        {
            string responseXml = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(properties.Address);
            if (properties.Timeout > 0) req.Timeout = properties.Timeout;
            byte[] request_bytes = System.Text.Encoding.UTF8.GetBytes(requestContent);
            req.Method = properties.Method;//"POST";
            req.ContentType = properties.ContentType;//"text/xml,application/x-www-form-urlencoded
            req.ContentLength = request_bytes.Length;
            if (properties.Headers != null && properties.Headers.Length > 0)
            {
                foreach (string s in properties.Headers)
                {
                    string[] headerInfo = s.Split('|');
                    if (headerInfo.Length == 2)
                        req.Headers[headerInfo[0]] = headerInfo[1];
                }
            }
            CredentialCache cache = new CredentialCache();
            bool flag = false;
            if (!string.IsNullOrEmpty(properties.BasicAuthUserName) && !string.IsNullOrEmpty(properties.BasicAuthPassword))
            {
                cache.Add(new Uri(properties.Address), "Basic", new NetworkCredential(properties.BasicAuthUserName, properties.BasicAuthPassword));
                flag = true;
            }
            if (properties.UseDefaultCredential)
            {
                cache.Add(new Uri(properties.Address), "NTLM", (NetworkCredential)CredentialCache.DefaultCredentials);
                flag = true;
            }
            if (flag)
            {
                req.Credentials = cache;
            }
            req.UserAgent = properties.UserAgent;
            req.AllowAutoRedirect = properties.AllowAutoRedirect;
            req.AllowWriteStreamBuffering = properties.AllowWriteStreamBuffering;
            req.KeepAlive = properties.KeepAlive;
            req.Pipelined = properties.Pipelined;
            req.PreAuthenticate = properties.PreAuthenticate;
            req.Referer = properties.Referer;
            req.SendChunked = properties.SendChunked;
            req.TransferEncoding = properties.TransferEncoding;
            req.Accept = properties.Accept;
            req.Expect = properties.Expect;
            req.MediaType = properties.MediaType;

            Stream request_stream = req.GetRequestStream();
            request_stream.Write(request_bytes, 0, request_bytes.Length);
            request_stream.Close();
            try
            {
                HttpWebResponse response = (HttpWebResponse)req.GetResponse();
                responseXml = RequestHelper.GetResponse(response);
                response.Close();
            }
            catch (WebException exception)
            {
                if (exception.Response != null)
                {
                    responseXml = RequestHelper.GetResponse((HttpWebResponse)exception.Response);
                }
                else
                {
                    responseXml = exception.ToString();
                }
            }
            catch (Exception exception2)
            {
                responseXml = exception2.ToString();
            }
            return responseXml;
        }

        public static string GetResponse(WebResponse response)
        {
            Stream responseStream = response.GetResponseStream();
            StringBuilder builder = new StringBuilder();
            System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
            builder.Append(reader.ReadToEnd());
            string xml = builder.ToString();
            return GetTogether.Utility.Xml.XmlHelper.FormatXml(xml);
        }
    }
}
